package com.zhong.service;

import com.zhong.mapper.OrderMapper;
import com.zhong.model.Order;
import com.zhong.sao.AccountClient;
import com.zhong.sao.StorageClient;
import feign.FeignException;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author itsome on 2021-08-27 22:05:29
 */
@Slf4j
@Service
public class OrderServiceImpl {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private AccountClient accountClient;

    @GlobalTransactional
    public void create(Order order) {
        // 创建订单
        orderMapper.insert(order);
        try {
            // 扣库存
            storageClient.deduct(order.getCommodityCode(), order.getCount());
            // 扣款
            accountClient.debit(order.getUserId(), order.getMoney());
        } catch (FeignException e) {
            log.error("下单失败，原因:{}", e);
            throw new RuntimeException(e);
        }
    }
}
